package com.class05.fruit.servlets;


import com.class05.fruit.dao.FruitDAO;
import com.class05.fruit.dao.impl.FruitDAOImpl;
import com.class05.fruit.pojo.Fruit;
import com.class05.myssm.myspringmvc.ViewBaseServlet;
import com.class05.myssm.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class IndexServlet extends ViewBaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如果没有传页,默认指定第一页
        Integer pageNo = 1;
        String pageNOStr = req.getParameter("pageNo");
        //指定页码不为空
        if (StringUtil.isNotEmpty(pageNOStr)) {
            //把字符串类型的指定的第几页的数字转换为int类型
            pageNo = Integer.parseInt(pageNOStr);
        }
        //通过req对象调用getSession()方法获取session
        HttpSession session = req.getSession();
        session.setAttribute("pageNo", pageNo);
        FruitDAO fruitDAO = new FruitDAOImpl();
        List<Fruit> fruitList = fruitDAO.getFruitList(pageNo);
        session.setAttribute("fruitList", fruitList);
        //查询总数
        int fruitCount = fruitDAO.getFruitCount();
        //start:就是当前页的起始索引,pageSize就是每页的条数
        //currentPage:就是当前页
        // 公式:start=(currentPage-1)*pageSize
        //总页数
        int pageCount = (fruitCount + 5 - 1) / 5;
        //         总记录数           总页数
        //            1                1
        //            5                1
        //            6                2
        //            10               2
        //            11               3
        session.setAttribute("pageCount",pageCount);
        super.processTemplate("index",req,resp);
    }
}
